package com.cskaoyan.servlet;

import com.cskaoyan.bean.model.MarketAdmin;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.service.AdminServiceImpl;
import com.cskaoyan.util.JsonUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/auth/*")
public class AdminAuthServlet extends CommonServlet{
    public static final String USER_KEY = "market_user_id";

    AdminService adminService = new AdminServiceImpl();

    // login
    public BaseRespVo login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        Map<String,String> map = JsonUtil.read(jsonStr, Map.class);
        String username = map.get("username");
        String password = map.get("password");

        Integer adminId = adminService.login(username, password);
        if (adminId != 0) { // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute(USER_KEY, adminId);
            MarketAdmin marketAdmin = adminService.queryById(adminId);
            Map<String,Object> data = new HashMap<>();
            data.put("token", session.getId());
            HashMap<String, Object> adminInfo = new HashMap<>();
            adminInfo.put("avatar", marketAdmin.getAvatar());
            adminInfo.put("nickName", marketAdmin.getUsername());
            data.put("adminInfo", adminInfo);

            return BaseRespVo.ok(data); // CommonServlet中的method.invoke方法的返回值
        } else {
            return BaseRespVo.msg("用户名或密码错误");
        }

    }

    // logout
    public BaseRespVo logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        return BaseRespVo.msg("已注销");
    }
    // info
    public BaseRespVo info(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Integer adminId = (Integer) session.getAttribute(USER_KEY);

        MarketAdmin marketAdmin = adminService.queryById(adminId);
        Map<String,Object> data = new HashMap<>();
        data.put("avatar", marketAdmin.getAvatar());
        data.put("nickName", marketAdmin.getUsername());
        data.put("perms", Arrays.asList("*"));
        data.put("roles", JsonUtil.read(marketAdmin.getRoleIds(),Integer[].class));
        return BaseRespVo.ok(data);
    }
    // modify
    public BaseRespVo modify(HttpServletRequest request, HttpServletResponse response) {
        // 写修改业务代码
        return BaseRespVo.msg("修改成功");
    }
    // remove
    public BaseRespVo remove(HttpServletRequest request, HttpServletResponse response) {
        // 写删除业务代码
        return BaseRespVo.msg("删除成功");
    }

}
